package cn.wsalix.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Random;
import java.util.regex.Pattern;

import org.springframework.stereotype.Service;

import cn.anlaser.exception.NutException;

@Service("utils")
public class Utils {
	public static String Default_charSet = "UTF-8";

	public static int nextInt(final int min, final int max) {
		Random rand = new Random();
		int tmp = Math.abs(rand.nextInt());
		return tmp % (max - min + 1) + min;
	}

	public static String getCurrDir() {
		return decode(Utils.class.getClassLoader().getResource("").getPath());

	}

	public static String decode(String sourCode) {
		return decode(sourCode, Default_charSet);
	}

	public static String decode(String sourCode, String enc)
			throws NutException {
		try {
			return URLDecoder.decode(sourCode, enc);
		} catch (UnsupportedEncodingException e) {
			throw new NutException(e);
		}
	}

	public static String getBrowserByAgent(String agent) {
		if (getWxPattern().matcher(agent).find()) {//
			return "weixin";
		}
		if (getAliPattern().matcher(agent).find()) {//
			return "alipay";
		}

		return "";// BrowserUtils.decode(agent);
	}

	private static Pattern getAliPattern() {
		String aliRegEx = "aliapp|AliApp";
		return Pattern.compile(aliRegEx);
	}

	private static Pattern getWxPattern() {
		String aliRegEx = "micromessenger|MicroMessenger";
		return Pattern.compile(aliRegEx);
	}
}
